﻿using apiframworkTest.Common;
using apiframworkTest.Models;
using commonFramwork.Log;
using Myu.Interface.InterFace;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using JWT.Serializers;
using JWT;
using JWT.Algorithms;
using System.Text;
using commonFramwork.ValidataImage;
using commonFramwork.base64;
using apiframworkTest.Filter;
using System.Web.Http.Results;
using System.Web.Script.Serialization;
using My.BLL.NewService;
using Ef.Repository.Entity;
using commonFramwork.Response;
using System.IO;
using System.Threading.Tasks;
using dapper.Repository.Repository;
using dapper.Repository.entity.Dto;
using System.Data;
using dapper.Repository;
using My.BLL.DapperService;
using MongoDbRepository;
using Entity.Framework.Specifications;
using Entity.Framework;
using My.BLL.CacheService;

namespace apiframworkTest.Controllers
{
    public class TestController : ApiController
    {
        //public IMessageSend _messageSend = new UnityContainerHelp().GetServer<IMessageSend>();
        //public IAccountService _accountService = new UnityContainerHelp().GetServer<IAccountService>();

        //private  readonly INewMyServices _newMyService;

        private readonly IUserCacheService _userCacheService;


        private static MyuLogger loger = new MyuLogger(typeof(TestController));
        public TestController(IUserCacheService userCacheService)//INewMyServices newMyService, 
        {
          //  _newMyService = newMyService;
            _userCacheService = userCacheService;
        }

        // GET: api/Test
        [HttpGet]
        [AllowAnonymous]
        public IEnumerable<string> Get()
        {
            // _messageSend.SendMessage("s");
            //throw new Exception();




            //UserService service = new UserService();

            #region dapper
            UserService ff = new UserService();
            ff.TestTrans();
            //service.TestTrans();
            Entity.Framework.Respositories.UserRepository userRepository = new Entity.Framework.Respositories.UserRepository(new EntityFrameworkRepositoryContext());
            #endregion
            #region EF测试
            //try
            //{
            //    //var entity = userRepository.GetByKey(Guid.Parse("c69940bb-2912-43ad-a97f-d2eb6bffae40"));

            //    //var ss = userRepository.Find(new UsersSpecification("ccc"));

            //    //entity.UserName = "测试";
            //    //userRepository.Update(entity);

            //    userRepository.Add(new Repository.entity.User() { ID = Guid.NewGuid(), Email = "yny@qq.com", Password = "123qwe", UserName = "余宁艳" });

            //    userRepository.Context.Commit();
            //}
            //catch (Exception)
            //{w
            //    userRepository.Context.Rollback();
            //    throw;
            //}


            #region 缓存测试
            //try
            //{
            //    //_userCacheService.SetUserInfo(new Repository.entity.User() { ID = Guid.NewGuid(), Email = "yny@qq.com", Password = "123qwe", UserName = "于芓牧" });
            //    var users = _userCacheService.GetUserInfo();
            //    var ss = users;
            //}
            //catch (Exception)
            //{

            //    throw;
            //}
            #endregion

            #endregion



            #region mongoDb

            //MongoDBRepositoryContext mongoDBRepositoryContext = new MongoDBRepositoryContext(new MongoDBRepositoryContextSettings());
            //MongoDbRepository.UserRepository userRepository = new MongoDbRepository.UserRepository(mongoDBRepositoryContext);
            //var ss = userRepository.GetAll(x => x.Email == "xxxx@sina.com");
            //userRepository.Add();
            //userRepository.Context.Commit();
            //var result = userRepository.GetAll();

            #endregion



            //userRepository.TestTrans();

            //var ss = userRepository.GetById(2);
            //userRepository.Delete(ss);



            //var sss =  userRepository.GetByPageIndex(2, 4);
            //  var tab =  userRepository.GetDynimic<ClassUser>("select a.Id,a.Name,a.Code,b.ClassName from [dbo].[User] a,[dbo].[Classs] b where  a.ClassId = b.Id"); //
            //var user1 = new dapper.Repository.entity.User() { Code = "ccccc", Name = "dzcc" };
            //userRepository.Insert(user1);

            //var user = new dapper.Repository.entity.User() { Id=2, Code = "dzcc", Name = "tt" };
            //userRepository.Update(user);
            //var ss = userRepository.GetById(1);
            return new string[] { "value1", "value2" };
        }



        [HttpGet]
        [Route("api/Test/Login")]
        [AllowAnonymous]
        public object Login(string strUser, string strPwd)
        {
            if (!ValidateUser(strUser, strPwd))
            {
                return new { bRes = false };
            }
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0, strUser, DateTime.Now,
                            DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", strUser, strPwd),
                            FormsAuthentication.FormsCookiePath);
            //返回登录结果、用户信息、用户验证票据信息
            var oUser = new UserInfo { bRes = true, UserName = strUser, Password = strPwd, Ticket = FormsAuthentication.Encrypt(ticket) };
            //将身份信息保存在session中，验证当前请求是否是有效请求
            HttpContext.Current.Session[strUser] = oUser;
            return oUser;
        }

        [AllowAnonymous]
        [HttpPost]
        [Route("api/UploadFile")]
        public HttpResponseMessage UploadFile()
        {
            var files =   HttpContext.Current.Request.Files;

            foreach (string key in files.AllKeys)
            {
                HttpPostedFile file1 = files[key];
                if (string.IsNullOrEmpty(file1.FileName) == false)
                {
                    StreamReader reader = new StreamReader(file1.InputStream);
                    string text = reader.ReadToEnd();
                    return ResponseHelper.GetResponse<string>(text);
                }
            }

            return ResponseHelper.GetResponse<string>("");

        }



        [AllowAnonymous]
        [ValidataActionFilterAttribute]
        [HttpPost]
        [Route("api/Login")]
        public HttpResponseMessage MyuLogin([FromBody] LoginDto loginDto)
        {
            if (!ValidateUser(loginDto.UserName, loginDto.Password))
            {
                return ResponseHelper.GetResponse(new { bRes = false });
            }

            var key = ConfigurationManager.AppSettings["SecureKey"];
            var builder = new JWT.Builder.JwtBuilder();

            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializerf = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializerf, urlEncoder);

            AuthInfo authInfo = new AuthInfo() {
                IsAdmin = true,
                Roles = new List<string>() { "admin", "guest" },
                UserName = loginDto.UserName
            };

            byte[] keycode = Encoding.Default.GetBytes(key);

            var jwttoken = encoder.Encode(authInfo, keycode);


            var oUser = new UserInfo { bRes = true, UserName = loginDto.UserName, Password = loginDto.Password, Ticket = jwttoken };

            var ss = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"];

            HttpContext.Current.Session[loginDto.UserName] = oUser;

            HttpContext.Current.Session["xxxx"] = "zxczxcxzczxczxczxzxczx";

            return ResponseHelper.GetResponse<UserInfo>(oUser);


            #region basic 验证
            //if (!ValidateUser(loginDto.UserName, loginDto.Password))
            //          {
            //              return new { bRes = false };
            //          }
            //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0, loginDto.UserName, DateTime.Now,
            //                DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", loginDto.UserName, loginDto.Password),
            //                FormsAuthentication.FormsCookiePath);
            ////返回登录结果、用户信息、用户验证票据信息
            //var oUser = new UserInfo { bRes = true, UserName = loginDto.UserName, Password = loginDto.Password, Ticket = FormsAuthentication.Encrypt(ticket) };
            ////将身份信息保存在session中，验证当前请求是否是有效请求
            //HttpContext.Current.Session[loginDto.UserName] = oUser;
            //return oUser;
            #endregion

        }



        //校验用户名密码（正式环境中应该是数据库校验）
        private bool ValidateUser(string strUser, string strPwd)
        {
            if (strUser == "admin" && strPwd == "123456")
            {
                return true;
            }
            return false;
        }

        [AllowAnonymous]
        [HttpPost]
        [Route("api/Valid")]
        public string ValidataImage()
        {
          
            YZMHelper yZM = new YZMHelper();
            HttpContext.Current.Session.Add("validata", yZM.Text);
            return Base64Helper.ImgToBase64String(yZM.Image);
        }

        // GET: api/Test/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Test
        [HttpPost]
        public IEnumerable<string> Post([FromBody]string value)
        {
           // _accountService.CheckAuth("ss", "sss");

            return new string[] { "value1", "value2" };
        }

        // PUT: api/Test/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Test/5
        public void Delete(int id)
        {
        }

        public async Task<int> Test()
        {
            Console.WriteLine("sss");

            var ss =  await Task.Run(() =>
            {
                Console.WriteLine("ss");
                return 5;
            });
            return ss;
        }
    }
}
